package com.mall.b2c.controller;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.mall.common.exception.NoticeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.b2c.domain.goods.GoodsCategoryDomain;
import com.mall.b2c.service.GoodsCategoryService;
import com.mall.common.bean.WebErrors;
import com.mall.common.controller.BaseAuthController;
import com.mall.common.hibernate.Finder;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.IntRangeFieldValidator;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.Validations;


/**
 * @author wangzx
 * 后台Action类 - 商品
 */
@Controller
@RequestMapping("/admin/b2c/goodsCategory")
public class GoodsCategoryController  extends BaseAuthController{

	@Resource private GoodsCategoryService goodsCategoryService; 

	@RequestMapping(value="/main", method=RequestMethod.GET)
	public String main(){
		return "/admin/b2c/goodsCategory/main";
	}
	
	@RequestMapping(value="/input", method=RequestMethod.GET)
	public String input(Long goodsCategory_id, Model model){
		GoodsCategoryDomain goodsCategory = goodsCategoryService.find(goodsCategory_id);
		model.addAttribute("goodsCategory", goodsCategory);
		buttonAuth("add", "/admin/goodsCategory/save*", model);
		buttonAuth("update", "/admin/goodsCategory/update*", model);
		buttonAuth("delete", "/admin/goodsCategory/delete*", model);
		return "/admin/b2c/goodsCategory/input";
	}
	
	@RequestMapping(value="/tree", method=RequestMethod.GET)
	public String tree(){
		return "/admin/b2c/goodsCategory/tree";
	}
	
	@RequestMapping(value="/treeData", method=RequestMethod.POST)
	@ResponseBody
	public List<GoodsCategoryDomain> treeData(){
		String hql = "from GoodsCategoryDomain bean order by bean.priority";
		Finder f = Finder.create(hql);
		List<GoodsCategoryDomain> catList = f.findHQLList();
		GoodsCategoryDomain root = new GoodsCategoryDomain();
		root.setName("顶级分类");
		root.setHasChild(Boolean.TRUE);
		catList.add(root);
		return catList;
	}
	
	@RequestMapping(value="/edit", method=RequestMethod.GET)
	public String edit(Long goodsCategory_id, Model model){
		if(goodsCategory_id != null){
			GoodsCategoryDomain goodsCategory = goodsCategoryService.find(goodsCategory_id);
			model.addAttribute("goodsCategory", goodsCategory);
		}
		buttonAuth("add", "/admin/goodsCategory/save*", model);
		buttonAuth("update", "/admin/goodsCategory/update*", model);
		buttonAuth("delete", "/admin/goodsCategory/delete*", model);
		return "/admin/b2c/goodsCategory/input";
	}
	
	//保存
	@Validations(
		requiredStrings = { 
			@RequiredStringValidator(fieldName = "name", message = "分类名称不允许为空!"),
			@RequiredStringValidator(fieldName = "code", message = "分类编码不允许为空!")
		}, 
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "priority", message = "排序不允许为空!")
		},
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "priority", min = "0", message = "排序必须为零或正整数!")
		}
	)
	@RequestMapping(value="/save", method=RequestMethod.POST)
	public String save(GoodsCategoryDomain goodsCategory, HttpServletResponse response){
		GoodsCategoryDomain persistent = goodsCategoryService.get("code", StringUtils.substringBeforeLast(goodsCategory.getCode(), "."));
		if(persistent != null){
			goodsCategory.setParent(persistent);
		}
		if (!goodsCategoryService.isUnique("code", null, goodsCategory.getCode())) {
			WebErrors errors = WebErrors.create();
			errors.addErrorCode("admin.category.code.unique");
			return errors.showErrorAjax(response);
		}
		goodsCategoryService.persist(goodsCategory);
		return ResponseUtils.renderJSON(goodsCategory, response);
	}
	
    /**
	 * 删除类别
	 * @return
	 */
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	public String delete(Long[] ids, HttpServletResponse response){
		GoodsCategoryDomain persistent = goodsCategoryService.find(ids[0]);
		if(persistent!=null){
			if(!CollectionUtils.isEmpty(persistent.getGoodses())){
				throw new NoticeException("部分商品已关联此分类，不能进行删除操作");
			}
			Set<GoodsCategoryDomain> cates = persistent.getChildren();
			if(!CollectionUtils.isEmpty(cates)){
				for(GoodsCategoryDomain cate : cates){
					if(!CollectionUtils.isEmpty(cate.getGoodses())){
						throw new NoticeException("部分商品已关联此分类子分类，不能进行删除操作");
					}
				}
			}

		}
    	goodsCategoryService.remove(ids);
		return ResponseUtils.renderJSON(persistent, response);
    }
	
	// 更新
	@Validations(
		requiredStrings = { 
			@RequiredStringValidator(fieldName = "name", message = "分类名称不允许为空!"),
			@RequiredStringValidator(fieldName = "code", message = "分类编码不允许为空!")
		}, 
		requiredFields = { 
			@RequiredFieldValidator(fieldName = "priority", message = "排序不允许为空!")
		},
		intRangeFields = {
			@IntRangeFieldValidator(fieldName = "priority", min = "0", message = "排序必须为零或正整数!")
		}
	)
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(GoodsCategoryDomain goodsCategory, HttpServletResponse response){

		String parentCode = StringUtils.substringBeforeLast(goodsCategory.getCode(), ".");
		GoodsCategoryDomain parent = null;
		if(StringUtils.isNotEmpty(parentCode) && !parentCode.equals(goodsCategory.getCode())) {
			parent = goodsCategoryService.get("code", StringUtils.substringBeforeLast(goodsCategory.getCode(), "."));
		}
		GoodsCategoryDomain persistent = goodsCategoryService.find(goodsCategory.getId());
		if (parent != null && !goodsCategoryService.isUnique("code", persistent.getCode(), goodsCategory.getCode())){
			WebErrors errors = WebErrors.create();
			errors.addErrorCode("error.unique", "goodsCategory code");
			return errors.showErrorAjax(response);
		}
		
		if(parent != null){
			goodsCategory.setParent(parent);
		}
		goodsCategoryService.updateByUpdater(goodsCategory);
		return ResponseUtils.renderJSON(goodsCategory, response);
	}
}